  import 'dart:async';
  import 'dart:math';
  import 'package:flutter/material.dart';
  import 'package:get/get.dart';

  class RegisterLogic extends GetxController {
    final TextEditingController phoneController = TextEditingController();
    final TextEditingController codeController = TextEditingController();
    final TextEditingController passwordController = TextEditingController();
    final TextEditingController confirmPasswordController = TextEditingController();
    final RxBool isConfirmPasswordVisible = false.obs;
    final RxString confirmPasswordErrorText = "".obs;
    final RxString phone = "".obs;
    final RxString verifyCode = "".obs;
    final RxString password = "".obs;
    final RxString phoneErrorText = "".obs;
    final RxString codeErrorText = "".obs;
    final RxString passwordErrorText = "".obs;
    final RxInt countdown = 60.obs;
    final RxBool isRunning = false.obs;
    final RxBool showCaptcha = false.obs;
    final RxBool captchaVerified = false.obs;
    final RxString generatedCode = "".obs;
    final RxString confirmPassword = "".obs;
    final RxBool isPasswordVisible = false.obs;

    Timer? _timer;
    final Random _random = Random();

    @override
    void onInit() {
      super.onInit();
      generateNewCaptcha();
    }

    void showPuzzleCaptcha() {
      if (!_validatePhone(phone.value)) return;
      showCaptcha.value = true;
    }
    void onConfirmPasswordChanged(String value) {
      confirmPassword.value = value; // 存储确认密码
      confirmPasswordErrorText.value = ""; // 清空错误提示
    }
    void onCaptchaSuccess() {
      captchaVerified.value = true;
      showCaptcha.value = false;
      startCountdown();
    }

    void onPhoneChanged(String value) {
      if (value.length > 11) {
        phoneController.text = value.substring(0, 11);
        phoneController.selection = TextSelection.fromPosition(
          TextPosition(offset: phoneController.text.length),
        );
        return;
      }
      phone.value = value;
      phoneErrorText.value = "";
    }

    void onCodeChanged(String value) {
      verifyCode.value = value;
      codeErrorText.value = "";
    }

    void onPasswordChanged(String value) {
      password.value = value;
      passwordErrorText.value = "";
    }

    bool _validatePhone(String phone) {
      if (phone.isEmpty) {
        phoneErrorText.value = "请输入手机号码";
        return false;
      }
      if (phone.length != 11 || !RegExp(r'^[0-9]{11}$').hasMatch(phone)) {
        phoneErrorText.value = "请输入正确的,已被实名注册的手机号码";
        return false;
      }
      return true;
    }

    bool _validateCode(String code) {
      if (code.isEmpty) {
        codeErrorText.value = "请输入验证码";
        return false;
      }
      if (code.length < 4) {
        codeErrorText.value = "验证码至少4位";
        return false;
      }
      if (code != generatedCode.value) {
        codeErrorText.value = "验证码不正确";
        return false;
      }
      return true;
    }

    bool _validatePassword(String password) {
      if (password.isEmpty) {
        passwordErrorText.value = "请输入密码";
        return false;
      }
      return true;
    }

    bool _validateConfirmPassword(String confirmPassword) {
      if (confirmPassword.isEmpty) {
        confirmPasswordErrorText.value = "请确认密码";
        return false;
      }
      if (confirmPassword != password.value) {
        confirmPasswordErrorText.value = "两次输入的密码不一致";
        return false;
      }
      return true;
    }

    void generateNewCaptcha() {
      generatedCode.value = (1000 + _random.nextInt(9000)).toString();
      captchaVerified.value = false;
      debugPrint("生成的验证码: ${generatedCode.value}");
    }

    bool validateRegister() {
      final isPhoneValid = _validatePhone(phone.value);
      final isCodeValid = _validateCode(verifyCode.value);
      final isPasswordValid = _validatePassword(password.value);
      final isConfirmPasswordValid = _validateConfirmPassword(confirmPassword.value); // 新增验证
      return isPhoneValid && isCodeValid && isPasswordValid && isConfirmPasswordValid;
    }

    void startCountdown() {
      if (isRunning.value) return;

      isRunning.value = true;
      Get.snackbar(' 验证码已发送', '请注意查收',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.green,
          colorText: Colors.white);

      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        if (countdown.value == 0) {
          _resetCountdown();
        } else {
          countdown.value--;
        }
      });
    }

    void _resetCountdown() {
      _timer?.cancel();
      isRunning.value = false;
      countdown.value = 60;
    }

    @override
    void onClose() {
      phoneController.dispose();
      codeController.dispose();
      passwordController.dispose();
      _timer?.cancel();
      super.onClose();
    }
  }
